/**
 * 
 */
package com.dy.agent.agent.api.web.controller.utils;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dy.agent.agent.api.exception.BusinessException;
import com.dy.agent.agent.api.exception.CommonErrorCode;
import com.dy.agent.agent.api.web.controller.vo.ResultWrapper;

/**
 * @author leiruiqi
 *
 */
public class ControllerUtils {

	protected static Logger log = LoggerFactory.getLogger(ControllerUtils.class);

	public static interface ActionHandler {
		ResultWrapper<?> getResponse();
	}

	public static String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

	public static String getUserAgent(HttpServletRequest request) {
		return request.getHeader("User-Agent");
	}

	@SuppressWarnings("rawtypes")
	public static ResultWrapper<?> doHandler(ActionHandler handler, String actionName) {
		try {
			long current = System.currentTimeMillis();
			ResultWrapper<?> response = handler.getResponse();
			Object data = response.getResult();
			if (data instanceof Collection) {
				log.info("{}, result size:{}, cost:[{}ms]", actionName, ((Collection) data).size(),
						System.currentTimeMillis() - current);
			} else {
				if (log.isDebugEnabled()) {
					log.debug("{}, response data:{}, cost:[{}ms]", actionName, response.getResult(),
							System.currentTimeMillis() - current);
				} else {
					log.info("{}, cost:[{}ms]", actionName, System.currentTimeMillis() - current);
				}
			}
			return response;
		} catch (IllegalArgumentException e) {
			log.warn("catch illegal exception:", e);
			log.warn("{}, catch  IllegalArgumentException:{} {}", actionName, e, e.getMessage());
			return ResultUtils.asError(CommonErrorCode.PARAM_ERROR, e.getMessage());
		} catch (BusinessException e) {
			log.warn("catch  BusinessException:", e);
			log.warn("{}, catch  BussinessException:{} {}", actionName, e, e.getMessage());
			return ResultUtils.asError(e.getErrorCode(), e.getMessage());
		} catch (Exception e) {
			log.error("cat exception:", e);
			log.error("{}, catch  Exception:{} {}", actionName, e, e.getMessage());
			return ResultUtils.asError(CommonErrorCode.SYSTEM_ERROR, e.getMessage());
		}
	}
}
